<template>
  <div class="app-container">
    <div v-if="isShow" class="shou-fei-zhe-gai-ceng"><h1>预结算后不能修改页面操作</h1>
    </div>
    <div class="div-style">
      <el-divider content-position="left"><span class="divider-css">▶患者信息◀</span></el-divider>
      <div class="search-container" style="margin-bottom: 0">
        <el-form ref="formRef" :inline="true" :model="queryParams" label-width="80px" style="margin-top: 10px">
          <el-form-item label="门诊号:">
            <el-input ref="clinicNoInputRef" v-model="queryParams.clinicNo" clearable
                      placeholder="请输入门诊号检索"
                      style="width: 200px">
              <template #append>
                <el-button class="patient-button" type="primary"
                           @click="patientSelectClick">检索
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="患者姓名:">
            <div v-if="queryParams.id" style="width: 110px; flex: 1; margin-right: 15px">
              <span class="fz15 ml5" style="color: #5050e1">
                {{
                  queryParams.name
                }}<svg-icon :icon-class="dictStore.getMateDictInfo(
                  dictDataMap['sys_user_sex'],
                  queryParams.sex
                ).dictValue === '1'
                  ? 'man'
                  : 'woman'
                  " style="margin-left: 10px"/></span>
            </div>
            <el-link v-else type="primary" @click="patientSelectClick">请选择患者</el-link>
          </el-form-item>
          <el-form-item label="年龄:">
            <span v-if="queryParams.id" class="fz13" style="width: 140px">{{ queryParams.age }} 岁</span>
            <span v-else style="width: 140px">暂无</span>
          </el-form-item>
          <el-form-item label="就诊科室:">
            <span style="width: 110px">{{
                queryParams.deptName ? queryParams.deptName : "暂无"
              }}</span>
          </el-form-item>
          <el-form-item label="身份证号:">
            <span style="width: 120px">{{
                queryParams.idNo ? queryParams.idNo : "暂无"
              }}</span>
          </el-form-item>
          <el-form-item label="联系电话:">
            <span style="width: 80px">{{
                queryParams.phone ? queryParams.phone : "暂无"
              }}</span>
          </el-form-item>
          <el-row>
            <el-form-item label="费别:">
              <el-select v-model="queryParams.chargeType" placeholder="请选择费别" style="width: 200px"
                         @change="chargeTypeChange">
                <el-option v-for="dict in dictDataMap['medical_insurance_type']" :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="读卡类型:">
              <el-select v-model="queryParams.medicalReadCardType" :disabled="isNotMedical"
                         placeholder="读卡类型"
                         style="width: 120px">
                <el-option v-for="dict in dictDataMap['medical_read_card_type']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
              <el-button :disabled="isNotMedical" type="primary" @click="resetPatient('01306')">
                <svg-icon class="mr5" icon-class="readCard"/>
                读卡
              </el-button>
            </el-form-item>
            <el-form-item label="医保来源:">
              <el-select v-model="queryParams.source" :disabled="isNotMedical" style="width:  120px">
                         placeholder="请选择医保来源">
                <el-option v-for="dict in dictDataMap['patient_medical_source']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="业务类型:" label-width="117px">
              <el-select v-model="queryParams.ybSerialType" :disabled="isNotMedical" placeholder="业务类型"
                         style="width: 120px">
                <el-option v-for="dict in dictDataMap['outp_settlement_business_type_dict']"
                           :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="参保类型:">
              <el-select v-model="queryParams.canBaoType" :disabled="isNotMedical" placeholder="参保类型"
                         style="width: 120px">
                <el-option v-for="dict in dictDataMap['insurance_type']" :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <el-form-item label="结算方式:">
            <el-select v-model="queryParams.psnSetlway" :disabled="isNotMedical" placeholder="结算方式"
                       style="width: 200px">
              <el-option v-for="dict in dictDataMap['psn_setlway']" :key="dict.dictValue"
                         :label="dict.dictLabel"
                         :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="病种:">
            <el-select v-model="queryParams.diseCode" :disabled="isNotMedical" placeholder="请选择"
                       style="width: 200px" @change="handleDiseChange">
              <el-option v-for="(item, index) in diseList"
                         :key="index"
                         :label="item.osp_dise_name"
                         :value="item.osp_dise_code">
                <span>{{ `${item.osp_dise_code}-${item.osp_dise_name}` }}</span>
                <span v-if="item.enddate">{{ item.begndate }}</span>
                <span v-if="item.enddate">~{{ item.enddate }}</span>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-checkbox v-model="queryParams.individualAccount" :disabled="isNotMedical" class="ml20">个人账户余额支付
            </el-checkbox>
          </el-form-item>
          <el-form-item label="是否公账" prop="isPublicAccounts">
            <el-radio-group v-model="queryParams.isPublicAccounts">
              <el-radio v-for="dict in dictDataMap['sys_yes_no']"
                        :key="dict.dictValue"
                        :value="dict.dictValue">{{
                  dict.dictLabel
                }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="queryParams.isPublicAccounts === 'Y'" label="统一社会信用代码"
                        label-width="120" prop="unifiedSocialCreditCode">
            <el-input v-model="queryParams.unifiedSocialCreditCode" clearable
                      placeholder="请输入统一社会信用代码"/>
          </el-form-item>
          <!-- <el-row class="ml20"> -->
          <!--                    <el-form-item>
                                  <el-button :disabled="isNotMedical" plain type="primary" @click="medicalRegister">
                                      <svg-icon class="mr5" icon-class="register"/>
                                      医保登记
                                  </el-button>
                              </el-form-item>-->
          <!-- </el-row> -->
        </el-form>
      </div>
      <el-divider content-position="left"><span class="divider-css">▶费用信息◀</span></el-divider>
      <div style="display: flex; height: calc(100% - 131px)">
        <div class="div-style mr10" style="flex: 2.2">
          <div style="height: calc(50% - 15px)">
            <clinic-orders :clinic-id="queryParams.id" :org-id="queryParams.orgId"
                           @orders-selection-change="ordersSelectionChange"/>
          </div>

          <div style="height: calc(50% - 10px)">
            <clinic-orders-cost :orders-ids="ordersIdArray" @set-total-price="setTotalPrice"/>
          </div>
        </div>
        <div class="div-style" style="flex: 0.8;z-index: 2">
          <el-divider content-position="left"><span class="divider-css">▶结算信息◀</span></el-divider>
          <el-descriptions :border="true" :column="1" class="mt5 mr5 mb5 ml5">
            <el-descriptions-item min-width="200px">
              <template #label>
                <div class="cell-item">
                  <span class="ys-css">合计：</span>
                </div>
              </template>
              <span class="ys-css"> {{ totalPrice }}</span>元
            </el-descriptions-item>
          </el-descriptions>
          <el-row class="mt10">
            支付类型明细
            <div class="regist-info-div" style="
                height: calc(100% - 390px);
                background-color: #ffffff;
                position: relative;
              ">
              <div style="height: 300px; overflow-y: auto">
                <pay-way-list v-if="queryParams.id" ref="payWayListRef" :total-price="totalPrice"
                              :inp_or_outp="inpOrOutp" @set-net-receipts="payWayBlur"/>
                <div v-else style="
                    line-height: 105px;
                    position: absolute;
                    left: 50%;
                    transform: translateX(-50%);
                  ">
                  暂无数据
                </div>
              </div>
            </div>
          </el-row>
          <div style="margin-top: 30px">
            <el-descriptions :border="true" :column="1" class="mt5 mr5 mb5 ml5">
              <el-descriptions-item min-width="200px">
                <template #label>
                  <div class="cell-item">
                    <span class="ys-css">应收金额:</span>
                  </div>
                </template>
                <span class="ys-css"> {{ totalPrice }} </span>元
              </el-descriptions-item>
              <el-descriptions-item min-width="200px">
                <template #label>
                  <div class="cell-item">
                    <span class="ys-css">实收金额:</span>
                  </div>
                </template>
                <span class="ys-css"> {{ netReceipts }} </span>元
              </el-descriptions-item>
              <el-descriptions-item min-width="200px">
                <template #label>
                  <div class="cell-item">
                    <span class="ys-css">找&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;零:</span>
                  </div>
                </template>
                <span class="ys-css"> {{ retChange }} </span>元
              </el-descriptions-item>
            </el-descriptions>
          </div>
          <!--                    <el-button :disabled="isNotMedical" style="position: absolute; bottom: 35px; right: 230px" plain-->
          <!--                               type="primary" @click="medicalRegister">-->
          <!--                        <svg-icon class="mr5" icon-class="chargeOk"/>-->
          <!--                        结算-->
          <!--                    </el-button>-->
          <el-button plain v-if="isShow"
                     style="position: absolute; bottom: 35px; right: 251px"
                     type="danger" @click="cancelMedicalRegister">
            <svg-icon class="mr5" icon-class="chargeOk"/>
            取消医保预结算
          </el-button>
          <el-button v-if="!isNotMedical" :disabled="isNotMedical" plain
                     style="position: absolute; bottom: 35px; right: 140px"
                     type="success" @click="medicalRegister">
            <svg-icon class="mr5" icon-class="chargeOk"/>
            医保预结算
          </el-button>
          <el-button class="ml10" style="position: absolute; bottom: 35px; right: 40px" type="primary"
                     @click="chargeOk">
            <svg-icon class="mr5" icon-class="chargeOk"/>
            {{ isNotMedical ? '自费结算' : '医保结算' }}
          </el-button>
        </div>
      </div>
    </div>

    <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body :width="dialogWidth">
      <!-- 待收费患者选择弹出框 -->
      <patient-select v-if="dialogType==='patientSelectIndex'" ref="patientSelectRef" :api-source="'2'"
                      :org-id="queryParams.orgId"
                      @introduce="introduce"/>
      <template #footer>
              <span class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
              </span>
      </template>
    </el-dialog>

    <!--   读卡弹窗-->
    <ReadCardVue
        ref="readCardRef"
        :card-data="cardData"
    />

    <el-dialog v-model="dialogVisible" title="违规信息提示" width="60%">
      <!-- 违规名称和违规内容表格 -->
      <el-table :data="violationData" default-expand-all highlight-current-row row-key="jr_id" stripe
                style="width: 100%">
        <!-- 表头样式 -->
        <el-table-column type="expand">
          <template #default="props">
            <el-table :data="props.row.judge_result_detail_dtos" highlight-current-row stripe style="width: 100%">
              <el-table-column prop="jrd_id" label="详情ID" width="180" align="center" v-if="false"></el-table-column>
              <el-table-column align="center" label="处方ID" prop="rx_id" width="180"></el-table-column>
              <el-table-column align="center" label="违规项目类型" prop="vola_item_type" width="180"></el-table-column>
              <el-table-column align="center" label="违规金额" prop="vola_amt" width="180">
                <template #default="scope">
                  <span style="color: #999">{{ scope.row.vola_amt }}</span>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>

        <!-- 规则名称 -->
        <el-table-column align="center" label="规则名称" prop="rule_name" width="180">
          <template #default="scope">
            <span style="color: #333; font-weight: 500">{{ scope.row.rule_name }}</span>
          </template>
        </el-table-column>

        <!-- 违规内容 -->
        <el-table-column align="center" label="违规内容" prop="vola_cont" show-overflow-tooltip></el-table-column>

        <!-- 违规金额 -->
        <el-table-column align="center" label="违规金额" prop="vola_amt" width="120">
          <template #default="scope">
            <span style="color: #999">{{ scope.row.vola_amt }}</span>
          </template>
        </el-table-column>

        <!-- 严重程度 -->
        <el-table-column prop="sev_deg" label="严重程度" width="120" align="center"></el-table-column>

        <!-- 证据 -->
        <el-table-column align="center" label="证据" prop="vola_evid" show-overflow-tooltip
                         width="200"></el-table-column>

        <!-- 违规行为类型 -->
        <el-table-column prop="vola_bhvr_type" label="违规行为类型" width="120" align="center"></el-table-column>
      </el-table>

      <!-- 反馈原因 -->
      <div class="feedback-reason" style="margin-top: 20px;">
        <span style="font-weight: bold; color: #333">反馈原因</span>
        <el-radio-group v-model="feedbackReason" style="display: flex; flex-wrap: wrap; margin-top: 10px;">
          <el-radio label="紧急需要" style="margin-right: 20px; color: #666">紧急需要</el-radio>
          <el-radio label="病人自费" style="margin-right: 20px; color: #666">病人自费</el-radio>
          <el-radio label="病人强烈要求" style="margin-right: 20px; color: #666">病人强烈要求</el-radio>
          <el-radio label="特殊病种" style="margin-right: 20px; color: #666">特殊病种</el-radio>
          <el-radio label="其他" style="color: #666">其他</el-radio>
        </el-radio-group>
      </div>

      <!-- 按钮区域 -->
      <template #footer>
        <span class="dialog-footer" style="display: flex; justify-content: flex-end;">
          <el-button @click="feedback('1', feedbackReason)" style="margin-right: 10px;">继续保存</el-button>
          <el-button type="primary" @click="feedback('2', feedbackReason)">修改医嘱</el-button>
        </span>
      </template>
    </el-dialog>


  </div>
</template>

<script lang="ts">
export default {
  name: "OutpFees",
};
</script>

<script lang="ts" setup>
import clinicOrders from "@/views/clinicOrder/clinicOrders/index.vue";
import clinicOrdersCost from "@/views/clinicOrder/clinicOrdersCost/index.vue";
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";
import {listClinicMaster} from "@/api/patient/clinicMaster.ts";
import {addOutpFeesMaster} from "@/api/finance/outpFeesMaster.ts";
import {
  feedBack,
  getPatInfo, makeAnalysis,
  preSettlement,
  preSettlementUndo,
  priorAnalysis,
  settlement,
  slowSpecialWin
} from "@/api/msip/setl.ts";
import {invoiceEBillOutpatient} from "@/api/openApi/electronicInvoice/invoiceInvalidPaper.ts"
import axios from "axios";
import {ElLoading, ElMessage} from "element-plus";
import ReadCardVue from "@/views/msip/readCard/readCard.vue";
import readCardts, {MedicalCardData, ReadCardParams} from "@/api/msip/readCard.ts";
import {selectConfigByCache} from "@/api/system/orgConfig.ts";


const readCardRef = ref();
const apiDictType = ref(); //地区字典
const { idAuth } = readCardts();
const cardData = ref<MedicalCardData>();
// 便捷门诊 父组件函数调用
const emits = defineEmits(["convenientChargeOk"])
const useUserStore = useUserStoreHook();
const dictStore = useDictStoreHook();
const activeName = ref('info')
const isShow = ref(false)
// 弹出框类型
const dialogType = ref("patientSelectIndex");
const dialogWidth = ref("90%")
const payWayListRef = ref();
const clinicNoInputRef = ref();
const patientSelectRef = ref();
const {proxy} = getCurrentInstance() as any;
const inpOrOutp = ref<number>(1);
const patData = ref() //人员信息数据集
const infoList = ref([]);// 人员参保信息
const preSetlData = ref();  //预结算数据集
let fee_upload_sn = ref();  //费用上传流水号
let dynamic_ip = ref(); //客户端电脑ip
const mdtrt_cert_type = ref();//就诊凭证类型
const mdtrt_cert_no = ref("");//就诊凭证编号
let cardtoken = ref();//社保卡令牌
// 违规信息数据
const violationData = ref<any[]>([]);

// 结算号
const feesNo = ref("");
//事前事中类型
const warn_type = ref('1');
//事前事中违规id集合
const warn_rslt_ids = ref<any>([]);

const props = defineProps({
  //是否启用电子发票流程
  electronicInvoiceIsStartUsing: {
    type: String,
    default: "N"
  },
  //是否启用事前事中流程
  detailAuditIsStartUsing: {
    type: String,
    default: "N"
  },
})

let dictDataMap = ref(
  dictStore.isTypeGetData(
    "patient_medical_source",
    "medical_insurance_type",
    "sys_user_sex",
    "nation_dict",
    "medical_read_card_type",
    "outp_settlement_business_type_dict",
    "insurance_type",
    "psn_setlway",
    "cvlserv_flag",
    "psn_type",
    "psn_insu_stas",
    "psn_idet_type",
    "psn_type_lv",
    "sys_yes_no"
  )
);

// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
// 患者是否医保信息，按钮禁用
const isNotMedical = ref(true);
const open = ref<boolean>(false);
// 违规弹窗显示状态
const dialogVisible = ref<boolean>(false);
const title = ref<string>("待收费患者列表");
// 应收总金额
const totalPrice = ref<number>(0.0);
// 实收金额
const netReceipts = ref<number>(0.0);
// 找零
const retChange = ref<number>(0.0);
// 反馈原因
const feedbackReason = ref(''); // 默认为空
const diseList = ref<any>([])

// 主记录多选数组
const ordersIdArray = ref<any>([]);
const queryParams = ref<any>({
  chargeType: "1",
  medicalReadCardType: "1",
  orgId: userInfo.orgId,
  // 是否使用个人账户余额
  individualAccount: true,
  clinicNo: "",
  source: "",
  patientId: "",
  registId: "",
  sex: "1",
  age: 0,
  ageMonth: 0,
  ageDay: 0,
  ageHours: 0,
  ageMinutes: 0,
  phone: "",
  // 门诊结算业务类型
  ybSerialType: "4",
  psnSetlway: "01",
  canBaoType: "",
  diseCode: "",
  diseName: "",
});

function handleClick(tab: any, event: Event) {
  console.log(tab.props.name)
  console.log(tab.props.label)
}

// 在获取慢特病备案信息的方法中添加watch监听
/*watch(diseList, (newVal) => {
  if (newVal.length > 0) {
    queryParams.value.diseCode = newVal[0].osp_dise_code
    queryParams.value.diseName = newVal[0].osp_dise_name
  }
}, { immediate: true })*/

// 门诊号检索事件
function clinicNoBlur() {
  const param = {
    clinicNo: queryParams.value.clinicNo,
    orgId: queryParams.value.orgId,
    id: queryParams.value.clinicId,
    chargeFlag: queryParams.value.chargeFlag
  };
  queryParams.value = {}
  listClinicMaster(param).then((res: resType) => {
    const data = res.data as any;
    if (data.length > 0) {
      queryParams.value = data[0];
      if (queryParams.value.chargeType !== "1") {
        isNotMedical.value = false;
        queryParams.value.individualAccount = true;
        queryParams.value.psnSetlway = "01";
        queryParams.value.ybSerialType = "11";
      } else {
        isNotMedical.value = true;
        queryParams.value.individualAccount = false;
      }
      nextTick(() => {
        payWayListRef.value.initPayWayDictSelect()
        // 添加第一行支付方式：现金
        payWayListRef.value.inpSetFirstPayWay()
      })
    } else {
      ElMessage.error("没有这个患者，请输入正确的门诊号");
    }
  });
}

// 主记录多选勾选事件
function ordersSelectionChange(ordersIds: any) {
  ordersIdArray.value = ordersIds;
}

function patientSelectClick() {
  open.value = true;
  title.value = "待收费患者列表"
  dialogType.value = "patientSelectIndex"
  nextTick(() => {
    const param = {
      chargeFlag: "1",
    };
    patientSelectRef.value.getParentList(param);
  });
}

//取消预结算
function cancelMedicalRegister() {
  if (patData.value && preSetlData.value) {
    let param = {
      mdtrt_id: preSetlData.value.setlinfo.mdtrt_id,
      fee_upload_sn: fee_upload_sn.value,
      psn_no: patData.value.baseinfo.psn_no,//人员编号
      dynamic_ip: dynamic_ip.value,//动态ip
      his_user_id: userInfo.userId,//HIS 用户ID
      org_id: userInfo.orgId,//HIS 机构ID
      his_mdtrt_id: queryParams.value.id,//HIS ID
      his_mdtrt_no: queryParams.value.clinicNo,//HIS 门诊号
      source: "1",//来源
    };
    preSettlementUndo(param).then((res: resType) => {
      if (res && res.code === 200) {
        preSetlData.value = null;
        ElMessage.success("取消预结算成功");
        isShow.value = false
      } else {
        return ElMessage.error(res.msg)
      }
    });
  } else {
    ElMessage.success("取消预结算成功");
    isShow.value = false
  }
}

// 医保预结算
function medicalRegister() {
  if (!patData.value) {
    return ElMessage.error('请读卡进行身份认证！');
  }
  if (preSetlData.value) {
    return ElMessage.error('此患者已预结算！');
  }
  //患者身份校验
  let _psn_cert_type = patData.value.baseinfo.psn_cert_type;
  let _certno = patData.value.baseinfo.certno;
  let _psn_name = patData.value.baseinfo.psn_name;
  if (queryParams.value.idNo && _psn_cert_type == '01' && queryParams.value.idNo != _certno) {
    return ElMessage.error('患者【' + queryParams.value.name + '】与持卡人【' + _psn_name + '】身份证号不符，请核实！！！');
  }
  if (queryParams.value.name != _psn_name) {
    return ElMessage.error('患者【' + queryParams.value.name + '】与持卡人【' + _psn_name + '】姓名不符，请核实！！！');
  }
  // 组织参数
  let param = {
    his_mdtrt_id: queryParams.value.id,//HIS ID
    his_mdtrt_no: queryParams.value.clinicNo,//HIS 门诊号
    med_type: queryParams.value.ybSerialType,//医疗类别
    order_ids: ordersIdArray.value,//HIS 费用id
    charge_flag: '1',//his收费标志 待收费
    his_user_id: userInfo.userId,//HIS 用户ID
    org_id: userInfo.orgId,//HIS 机构ID
    mdtrt_cert_type: mdtrt_cert_type.value,//就诊凭证类型
    mdtrt_cert_no: mdtrt_cert_no.value,//就诊凭证号
    acct_used_flag: queryParams.value.individualAccount ? '1' : '0',// 个人账户使用标志
    medfee_sumamt: totalPrice.value,//HIS总费用
    psn_setlway: queryParams.value.psnSetlway,//个人结算方式
    dise_codg: queryParams.value.diseCode,//病种编码
    dise_name: queryParams.value.diseName,//病种名称
    tcm_dise_no: "",//中医适宜技术诊断编码
    psn_no: patData.value.baseinfo.psn_no,//人员编号
    insutype: queryParams.value.canBaoType,//险种类型
    cardtoken: cardtoken.value,//cardtoken-读卡返回
    psn_info: patData.value,//人员参保信息-1101返参
    dynamic_ip: dynamic_ip.value,//动态ip
    birctrl_type: "",//计划生育手术类别
    birctrl_matn_date: "",//计划生育手术日期
  };
  preSettlement(param).then((res: resType) => {
    if (res && res.code === 200) {
      preSetlData.value = res.data.output;
      fee_upload_sn.value = res.data.params.fee_upload_sn;//费用上传流水号
      // 校验费用
      let his_medfee_sumamt = totalPrice.value;
      if (his_medfee_sumamt != preSetlData.value.setlinfo.medfee_sumamt) {
        return ElMessage.error("HIS总费用【" + his_medfee_sumamt + "】与医保总费用【" + preSetlData.value.setlinfo.medfee_sumamt + "】不一致！请取消重新预结算！");
      }
      //组织支付方式
      setPays();
      if (props.detailAuditIsStartUsing === "Y") {
        // 调用事前事中审核
        preAudit();
      }
      isShow.value = true
      ElMessage.success("预结算成功");
    } else {
      return ElMessage.error(res.msg)
    }
  });
}

/**
 * 事前审核
 */
function preAudit() {
  if (!queryParams.value.id) {
    return ElMessage.error("请先选择需要收费的患者。");
  }
  if (!patData.value) {
    return ElMessage.error('请读卡进行身份认证！');
  }
  if (!preSetlData.value) {
    return ElMessage.error('请先进行预结算！');
  }
  // 组织参数
  let param = {
    his_user_id: userInfo.userId,//HIS 用户ID
    org_id: userInfo.orgId,//HIS 机构ID
    his_mdtrt_id: queryParams.value.id,//HIS ID
    order_ids: ordersIdArray.value,//HIS 费用id
    mdtrt_id: preSetlData.value.setlinfo.mdtrt_id,
    source: "1",//来源 门诊
    trig_scen: "2",//场景 门诊收费登记
    medfee_sumamt: totalPrice.value,//HIS总费用
    acct_payamt: preSetlData.value.setlinfo.acct_pay,//个人账户
    ma_amt: preSetlData.value.setlinfo.maf_pay,//救助金
    hifp_payamt: preSetlData.value.setlinfo.hifp_pay,//统筹金额
    dynamic_ip: dynamic_ip.value,//动态ip
  };
  priorAnalysis(param).then((res: resType) => {
    if (res && res.code === 200) {
      if (res.data.output.result?.length > 0) {
        debugger
        violationData.value = res.data.output.result;
        warn_type.value = "1";
        warn_rslt_ids.value = res.data.output.result.map(item => item.jr_id);
        dialogVisible.value = true;
        ElMessage.success("发现违规行为，请处理！");
      } else {
        ElMessage.success("未发现违规行为，分析完成！");
        //事前未发现错误调用事中审核
        makeAudit();
      }
    } else {
      ElMessage.error(res?.msg || "分析失败");
    }
  });
}

/**
 * 事中审核
 */
function makeAudit() {
  if (!queryParams.value.id) {
    return ElMessage.error("请先选择需要收费的患者。");
  }
  if (!patData.value) {
    return ElMessage.error('请读卡进行身份认证！');
  }
  if (!preSetlData.value) {
    return ElMessage.error('请先进行预结算！');
  }
  // 组织参数
  let param = {
    his_user_id: userInfo.userId,//HIS 用户ID
    org_id: userInfo.orgId,//HIS 机构ID
    his_mdtrt_id: queryParams.value.id,//HIS ID
    order_ids: ordersIdArray.value,//HIS 费用id
    mdtrt_id: preSetlData.value.setlinfo.mdtrt_id,
    source: "1",//来源 门诊
    trig_scen: "6",//场景 门诊收费登记
    medfee_sumamt: totalPrice.value,//HIS总费用
    ownpay_amt: preSetlData.value.setlinfo.fulamt_ownpay_amt,//自费金额
    selfpay_amt: preSetlData.value.setlinfo.preselfpay_amt,//自付金额
    acct_payamt: preSetlData.value.setlinfo.acct_pay,//个人账户
    ma_amt: preSetlData.value.setlinfo.maf_pay,//救助金
    hifp_payamt: preSetlData.value.setlinfo.hifp_pay,//统筹金额
    dynamic_ip: dynamic_ip.value,//动态ip
  };
  makeAnalysis(param).then((res: resType) => {
    if (res && res.code === 200) {
      if (res.data.output.result?.length > 0) {
        violationData.value = res.data.output.result;
        warn_type.value = "2";
        warn_rslt_ids.value = res.data.output.result.map(item => item.jr_id);
        dialogVisible.value = true;
        ElMessage.success("发现违规行为，请处理！");
      } else {
        ElMessage.success("未发现违规行为，分析完成！");
      }
    } else {
      ElMessage.error(res?.msg || "分析失败");
    }
  });
}


/**
 * 事前事中服务反馈服务
 * @param dspo_way 处理方式 1.继续执行医嘱 2.返回修改医嘱
 * @param dspo_way_rea 处理原因
 */
function feedback(dspo_way, dspo_way_rea) {
  if (!dspo_way_rea) {
    return ElMessage.error("请选择处理原因");
  }
  // 组织参数
  let param = {
    his_user_id: userInfo.userId,//HIS 用户ID
    org_id: userInfo.orgId,//HIS 机构ID
    warn_type: warn_type.value,//反馈类型 1 事前 2 事中
    warn_rslt_ids: warn_rslt_ids.value,//违规标识
    dspo_way: dspo_way,//处理方式 1.继续执行医嘱 2.返回修改医嘱
    dspo_way_rea: dspo_way_rea,//处理原因 如果为dspoWay为1必填
    dynamic_ip: dynamic_ip.value,//动态ip
  };
  feedBack(param).then((res: resType) => {
    if (res && res.code === 200) {
      ElMessage.success("反馈成功");
      dialogVisible.value = false; // 关闭弹窗
    } else {
      ElMessage.error(res.msg);
    }
  });
}

// 获取ybt配置文件ip
function getYBTIp() {
  axios.post(proxy.$ybtUrl + '/get_ybt_ip', "").then(async (res) => {
    if (res && res.data.code === 0) {
      dynamic_ip.value = res.data.data;
    } else {
      ElMessage.error(res.data.data)
    }
  }).catch((r) => {
    ElMessage.error('请检查医保终端是否打开~！');
  })
}

/**
 * 通过orgId key获取ApiDictType
 */
function selectApiDictType() {
  selectConfigByCache(userInfo.orgId, "api_dict_type").then((res => {
    apiDictType.value = res.data.configValue
  }));
}

/**
 * 预结算-支付方式赋值
 */
function setPays() {
  const setlinfo = preSetlData.value.setlinfo;
  let datas: any = [];
  //基金支付总额
  const fund_pay_sumamt = setlinfo.fund_pay_sumamt;
  if (fund_pay_sumamt && fund_pay_sumamt != 0) {
    const data = {
      dictValue: '6',
      charges: Number(fund_pay_sumamt).toFixed(2),
      sort: 1,
      disabled: true
    };
    datas.push(data);
  }
  //医院负担金额
  const hosp_part_amt = setlinfo.hosp_part_amt;
  if (hosp_part_amt && hosp_part_amt != 0) {
    const data = {
      dictValue: 'H01',
      charges: Number(hosp_part_amt).toFixed(2),
      sort: 2,
      disabled: true
    };
    datas.push(data);
  }
  //个人账户支出
  const acct_pay = setlinfo.acct_pay;
  if (acct_pay && acct_pay != 0) {
    const data = {
      dictValue: '3',
      charges: Number(acct_pay).toFixed(2),
      sort: 3,
      disabled: true
    };
    datas.push(data);
  }
  //个人现金
  const psn_cash_pay = setlinfo.psn_cash_pay;
  if (psn_cash_pay && psn_cash_pay != 0) {
    const data = {
      dictValue: '5',
      charges: Number(psn_cash_pay).toFixed(2),
      sort: 4,
      disabled: false
    };
    datas.push(data);
  }
  payWayListRef.value.tissuePayWayArray(datas);
}

/** 读卡 */
async function resetPatient(businesstype) {
  if (!queryParams.value.medicalReadCardType) {
    return ElMessage.error("请选择读卡类型！");
  }
  mdtrt_cert_type.value = '0' + queryParams.value.medicalReadCardType;
  mdtrt_cert_no.value = queryParams.value.idNo;
  try {
    const params: ReadCardParams = {
      mdtrt_cert_type: mdtrt_cert_type.value, //就诊凭证类型: 01=医保电子凭证 02=居民身份证 03=社会保障卡 04=终端扫码 05=终端扫脸
      cardtype: "0",//卡片类型: 0=实体卡 1=电子社保卡 mdtrt_cert_type 为“03”时必填
      businesstype: businesstype, //用码业务类型: 01301=结算 mdtrt_cert_type 为“01”时必填
      operatorid: userInfo.userId, //收款员编号 mdtrt_cert_type 为“01”时必填
      operatorname: userInfo.userName, //收款员姓名 mdtrt_cert_type 为“01”时必填
      officeid: "",//医保科室编号 mdtrt_cert_type 为“01”时必填
      officename: "",//科室名称 mdtrt_cert_type 为“01”时必填
      org_id: userInfo.orgId, //机构id
      name: queryParams.value.name,
      idNo: queryParams.value.idNo,
      his_user_id: userInfo.userId, //用户id
      dynamic_ip: dynamic_ip.value,
    };
    const res = await idAuth(params,apiDictType.value,mdtrt_cert_no)
    cardData.value = res;
    // 页面数据赋值
    patData.value = res;
    infoList.value = patData.value.insuinfo;
  } catch (err) {
    ElMessage.error('读卡失败，请检查终端连接');
  }
  // 使用for循环为参保类型赋值
  infoList.value.forEach((item, index) => {
    infoList.value[index] = item;
    if (item.psn_insu_stas == 1) {
      queryParams.value.canBaoType = item.insutype;
    }
  });
  //获取人员备案信息
  getSlowSpecialList(patData.value.baseinfo.psn_no);
  nextTick(() => {
    readCardRef.value.show(); // 确保数据赋值后再显示弹窗
  });
}


// 获取人员备案信息
function getSlowSpecialList(psn_no) {
  let _rd_insuplc_admdvs = '';
  // 使用for循环为参保区划赋值
  infoList.value.forEach((item, index) => {
    infoList.value[index] = item;
    if (item.psn_insu_stas == 1) {
      _rd_insuplc_admdvs = item.insuplc_admdvs;
    }
  });

  const param = {
    psn_no: psn_no,//人员编号
    org_id: userInfo.orgId,//机构ID
    his_user_id: userInfo.userId,//用户id
    insuplc_admdvs: _rd_insuplc_admdvs,//参保地区编码
    dynamic_ip: dynamic_ip.value,//当前电脑ip
  }
  slowSpecialWin(param).then((res: resType) => {
    if (res && res.code === 200) {
      // 处理返回数据
      if (res.data?.output?.feedetail?.length > 0) {
        diseList.value = res.data.output.feedetail.map(item => ({
          osp_dise_code: item.opsp_dise_code,
          osp_dise_name: item.opsp_dise_name,
          begndate: item.begndate,
          enddate: item.enddate
        }));
        ElMessage.success("查询到患者有慢特病备案信息，请注意医保业务类型！");
      } else {
        ElMessage.error("未查到病种备案信息");
        diseList.value = []; // 无数据时清空列表
      }
    } else {
      ElMessage.error(res.msg);
      diseList.value = [];
    }
  });
}


// 选择备案信息同时进行名称code赋值
function handleDiseChange(val) {
  const selectedDise = diseList.value.find(item => item.osp_dise_code === val);
  if (selectedDise) {
    queryParams.value.diseName = selectedDise.osp_dise_name;
  } else {
    queryParams.value.diseName = "";
  }
}

onMounted(() => {
  // 绑定监听事件
  window.addEventListener("keydown", keyDown);
  //获取医保地区自字典
  selectApiDictType();
  //获取ybt的ip地址
  getYBTIp();
});
onUnmounted(() => {
  // 销毁事件
  window.removeEventListener("keydown", keyDown, false);
});
// 点击回车键
const keyDown = (e: any) => {
  if (e.keyCode === 13) {
    // 获取input 是否存在焦点
    const querySelector = clinicNoInputRef.value.$el.querySelector("input");
    const isFocused = document.activeElement === querySelector;
    if (isFocused) clinicNoBlur();
  }
};

// 根据支付方式填写的金额自动计算应收和找零
function autoChargeFun() {
  retChange.value = Number((netReceipts.value - totalPrice.value).toFixed(2));
}

// 支付方式input金额焦点消失事件
function payWayBlur(netReceiptsThis: number) {
  netReceipts.value = Number(netReceiptsThis);
  autoChargeFun();
}

function setTotalPrice(totalPriceThis: number) {
  totalPrice.value = Number(Number(totalPriceThis).toFixed(2));
  nextTick(() => {
    if (payWayListRef.value) {
      const payWayDictList = payWayListRef.value.getPayWayDictList();
      payWayListRef.value.initPayWayDictSelect()
      if (payWayDictList.length === 1) {
        payWayListRef.value.setFirstCost(totalPriceThis);
      } else {
        payWayListRef.value.removePayWayAll()
        payWayListRef.value.inpSetFirstPayWay()
        payWayListRef.value.setFirstCost(totalPriceThis);
      }
      payWayListRef.value.payWayChange("5", 0);
      payWayListRef.value.payWayBlur();
    }
  });
}

/** 引用患者信息 */
function introduce(row) {
  queryParams.value.id = row.id;
  queryParams.value.orgId = row.orgId;
  queryParams.value.clinicNo = row.clinicNo;
  clinicNoBlur();
  cancel();
}

/**费别点击事件 */
function chargeTypeChange(value: string) {
  if (value === "1") {
    isNotMedical.value = true;
    queryParams.value.ybSerialType = "4";
    queryParams.value.individualAccount = false;
    queryParams.value.psnSetlway = "";
  } else {
    isNotMedical.value = false;
    queryParams.value.individualAccount = true;
    queryParams.value.psnSetlway = "01";
    queryParams.value.ybSerialType = "11";
  }
}

// 待收费患者选择弹出框
function cancel() {
  open.value = false;
}

// 确认收费
function chargeOk() {
  const submitForm = {};
  if (!queryParams.value.id) {
    return ElMessage.error("请先选择需要收费的患者。");
  }
  if (ordersIdArray.value.length <= 0) {
    return ElMessage.error("请勾选需要收费的项目后再进行收费操作。");
  }
  if (retChange.value < 0) {
    return ElMessage.error(
      "实收金额小于应收金额，请检查费用信息是否正确，检查输入无误后再进行收费操作。"
    );
  }
  let payWayInfoList = payWayListRef.value.getPayWayDictList();
  let selfPayAmount = 0;
  payWayInfoList.forEach((payWay: any) => {
    payWay.orgId = queryParams.value.orgId;
    if (!['6', 'H01', '3'].includes(payWay.dictValue)) {
      selfPayAmount += Number(payWay.charges) || 0;
    }
  });
  selfPayAmount = Number(selfPayAmount.toFixed(2));
  //医保结算
  if (!isNotMedical.value) {
    const confirmMessage = selfPayAmount > 0
      ? `患者存在需要自费部分，金额为<span style="font-size: 50px; color: #ff4444">【¥${selfPayAmount}】</span>，请注意确认`
      : "患者无自费部分，是否直接医保结算？";
    ElMessageBox.confirm(confirmMessage, {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true // 确保解析 HTML
    }).then(() => {
      //  组织参数
      let param = {
        mdtrt_id: preSetlData.value.setlinfo.mdtrt_id,
        his_mdtrt_id: queryParams.value.id,//HIS ID
        his_mdtrt_no: queryParams.value.clinicNo,//HIS 门诊号
        order_ids: ordersIdArray.value,//HIS 费用id
        his_user_id: userInfo.userId,//HIS 用户ID
        org_id: userInfo.orgId,//HIS 机构ID
        med_type: queryParams.value.ybSerialType,//医疗类别
        mdtrt_cert_type: mdtrt_cert_type.value,//就诊凭证类型
        mdtrt_cert_no: mdtrt_cert_no.value,//就诊凭证号
        acct_used_flag: queryParams.value.individualAccount ? '1' : '0',// 个人账户使用标志
        medfee_sumamt: totalPrice.value,//HIS总费用
        psn_setlway: queryParams.value.psnSetlway,//个人结算方式
        fulamt_ownpay_amt: preSetlData.value.setlinfo.fulamt_ownpay_amt,
        overlmt_selfpay: preSetlData.value.setlinfo.overlmt_selfpay,
        preselfpay_amt: preSetlData.value.setlinfo.preselfpay_amt,
        inscp_scp_amt: preSetlData.value.setlinfo.inscp_scp_amt,
        pays: payWayInfoList,
        cardtoken: cardtoken.value,//cardtoken-读卡返回
        psn_no: patData.value.baseinfo.psn_no,//人员编号
        insutype: queryParams.value.canBaoType,//险种类型
        chrg_bchno: fee_upload_sn.value,
        dise_codg: queryParams.value.diseCode,//病种编码
        dise_name: queryParams.value.diseName,//病种名称
        dynamic_ip: dynamic_ip.value,//动态ip
        pre_setl_data: preSetlData.value,//预结算信息
      };
      settlement(param).then((res: resType) => {
        if (res && res.code === 200) {
          if (res.data.infcode === 2) {
            isShow.value = true;
            againSetl(res.data.output);
          } else {
            nextTick(() => {
              payWayListRef.value.initPayWayDictSelect()
            })
            queryParams.value.clinicId = ""
            const canBaoType = queryParams.value.canBaoType;
            clinicNoBlur()
            queryParams.value.canBaoType = canBaoType;
            isNotMedical.value = true;
            netReceipts.value = 0.0;
            // 便捷门诊 父组件函数调用
            emits("convenientChargeOk")
            isShow.value = false;
            preSetlData.value = null;
            ElMessage.success("收费成功");
            feesNo.value = res.data.params.his_serial_no;
            if (props.electronicInvoiceIsStartUsing === "Y") {
              // 调用电子发票
              invoiceEBillOutpatientFun();
            }
          }
        } else {
          return ElMessage.error(res.msg)
        }
      });
    });
  } else {
    // 自费结算
    ElMessageBox.confirm("确定要收费吗？", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      let submitForm: any = {};
      submitForm.payWayInfoList = payWayInfoList;
      submitForm.outpFeesMasterBo = {
        orgId: queryParams.value.orgId,
        clinicId: queryParams.value.id,
        patientId: queryParams.value.patientId,
        visitDate: proxy.$parseTime(queryParams.value.visitDate),
        ybSerialType: queryParams.value.ybSerialType,
        canBaoType: queryParams.value.canBaoType,
      };
      submitForm.ordersIdList = ordersIdArray.value;
      addOutpFeesMaster(submitForm).then((res: resType) => {
        nextTick(() => {
          // payWayListRef.value.getPayWayDictList();
          payWayListRef.value.initPayWayDictSelect()
        })
        queryParams.value.clinicId = ""
        clinicNoBlur()
        isNotMedical.value = true;
        netReceipts.value = 0.0;
        // 便捷门诊 父组件函数调用
        emits("convenientChargeOk")
        ElMessage.success("收费成功");
        feesNo.value = res.data
        if (props.electronicInvoiceIsStartUsing === "Y") {
          // 调用电子发票
          invoiceEBillOutpatientFun();
        }
      });
    });
  }
}

/**
 * 判断是否为公共账户，是的话弹出输入公账信息的弹窗
 */
function isPublicAccountsByShow() {

}

/**
 * 医疗门诊电子票据开具接口
 */
function invoiceEBillOutpatientFun() {
  const data = {
    // 正常收款
    isRedFlush: "1",
    orgId: userInfo.orgId,
    feesNo: feesNo.value,
    // 门诊电子票据开具
    oupOrInp: "1",
  }
  invoiceEBillOutpatient(data).then((res: resType) => {
    if (res.data.code === "200") {
      ElMessage.success(res.data.msg);
      prescPrint();
    } else {
      ElMessage.error(res.data.msg)
    }
  })
}

/**
 * 小票打印
 */
const objectUrl = ref("")

function prescPrint() {
  let url = "/business/outpFeesMaster/receiptPrint";
  const formData = new FormData()
  formData.append("feesNo", feesNo.value)
  formData.append("orgId", userInfo.orgId)
  // pdf打印 、打印预览
  proxy.$printPdfPublic(url, formData).then(res => {
    if (res) {
      objectUrl.value = URL.createObjectURL(res)
    } else {
      console.error('打印失败')
    }
  })
}

/**
 * 二次结算
 */
function againSetl(data) {
  ElMessageBox.confirm("此患者【预结算】报销金额与【正式结算】报销金额不符，是否继续结算？注：继续结算会将【正式结算】报销为准，请认真核对报销信息再次结算！！", {
    confirmButtonText: "继续",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    preSetlData.value = data;
    setPays();
  });
}

function reset() {
  queryParams.value = {
    chargeType: "1",
    medicalReadCardType: "1",
    orgId: userInfo.orgId,
    // 是否使用个人账户余额
    individualAccount: true,
    clinicNo: "",
    source: "",
    patientId: "",
    registId: "",
    sex: "1",
    age: 0,
    ageMonth: 0,
    ageDay: 0,
    ageHours: 0,
    ageMinutes: 0,
    phone: "",
    // 门诊结算业务类型
    ybSerialType: "4",
    psnSetlway: "01",
    canBaoType: "",
    diseCode: "",
    diseName: "",
  };
}

/**
 * 便捷门诊-》设置默认患者
 * @param clinicId
 */
function convenientClinicNoBlur(clinicId: string) {
  queryParams.value.clinicId = clinicId;
  clinicNoBlur()
}

defineExpose({
  convenientClinicNoBlur
})
</script>

<style scoped>
:deep(.el-divider--horizontal) {
  margin: 10px 0 10px 0;
}

.search-container {
  padding: 0;
}

:deep(.el-form--inline .el-form-item) {
  margin-bottom: 10px;
  margin-top: -5px;
}

:deep(.el-dialog__header) {
  margin-bottom: 0 !important;
}
</style>
